package com.example.design.item.vistor;

import com.example.design.item.composite.AbstractProductItem;
import com.example.design.item.composite.ProductComposite;
import com.example.design.utils.RedisUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//Concrete Visitor 具体访问者——删除商品类目操作
@Component
public class RemoveItemVisitor implements ItemVisitor<ProductComposite>{


    @Resource
    private RedisUtils redisUtils;


    @Override
    public ProductComposite visit(AbstractProductItem productItem) {
        ProductComposite delComposite = (ProductComposite) productItem;
        ProductComposite curComposite = (ProductComposite) redisUtils.get("items");
        //不可以删除根节点
        if (curComposite.getId() == delComposite.getId()){
            throw new UnsupportedOperationException("根节点不可删除");
        }
        //如果要删除的结点的父节点为当前结点,直接删除
        if (curComposite.getId() == delComposite.getPid()){
            curComposite.remove(delComposite);
            return curComposite;
        }
        //否则,递归删除
        delChild(delComposite,curComposite);
        return curComposite;
    }

    private void delChild(ProductComposite delComposite, ProductComposite curComposite) {
        for (AbstractProductItem item : curComposite.getChild()) {
            ProductComposite child = (ProductComposite) item;
            if (child.getId() == delComposite.getPid()){
                child.remove(delComposite);
                break;
            }else {
                delChild(delComposite,child);
            }
        }
    }
}
